package com.yugao.fintech.antelope.system.manager;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yugao.fintech.antelope.base.model.constants.TenantCons;
import com.yugao.fintech.antelope.base.model.module.tenant.TenantContextHolder;
import com.yugao.fintech.antelope.system.mapper.SysTenantUserMapper;
import com.yugao.fintech.antelope.system.model.entity.SysTenantUser;
import com.yugao.fintech.antelope.base.tenant.core.utils.TenantUtils;
import com.yugao.fintech.framework.assistant.utils.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Objects;


@Slf4j
@Component
public class SysTenantUserManager extends ServiceImpl<SysTenantUserMapper, SysTenantUser> {


    public void deleteByUseIds(List<Long> userIds) {
        if (CollectionUtils.isEmpty(userIds)) {
            return;
        }
        LambdaQueryWrapper<SysTenantUser> lqw = SysTenantUser.lqw().in(SysTenantUser::getUserId, userIds);
        this.remove(lqw);
    }

    /**
     * 删除租户下的全部用户
     */
    public void deleteAllUser() {
        Long tenantId = TenantContextHolder.get().getTenantId();
        if (TenantCons.SYSTEM_TENANT_ID.equals(tenantId) || Objects.isNull(tenantId)) {
            log.warn("正常删除非法租户 {} 下的用户, 已拦截", tenantId);
            return;
        }
        LambdaQueryWrapper<SysTenantUser> lqw = SysTenantUser.lqw();
        this.remove(lqw);
    }

    /**
     * 更新用户最后登录时间
     * @param userId 用户id
     */
    public void updateLastLoginTime(Long userId) {
        this.update(SysTenantUser.luw().eq(SysTenantUser::getUserId, userId).set(SysTenantUser::getLastLoginTime, new Date()));
    }

    public List<SysTenantUser> listByUserId(Long userId) {
        return TenantUtils.executeIgnore(TenantCons.Type.ALL, () -> {
            LambdaQueryWrapper<SysTenantUser> lqw = SysTenantUser.lqw().eq(SysTenantUser::getUserId, userId);
            return this.list(lqw);
        });
    }
}
